<template>
  <div class="app-container">
    <!-- 搜索筛选操作栏 -->
    <div class="filter-container clearfix">
      <el-button v-waves class="filter-item" @click="handleCreate">
        添加轮播图
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" ref="table" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="顺序" prop="order" align="center" />
      <el-table-column label="轮播图名称" prop="name" align="center" />
      <el-table-column label="图片" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 200px; height: 100px" :src="$store.state.settings.imgHost + row.image_url"
            :preview-src-list="[$store.state.settings.imgHost+row.image_url]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button size="mini" plain type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" plain type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加&编辑 -->
    <el-dialog :title="type == 0 ? '添加轮播图' : '编辑轮播图'" :visible.sync="dialogVisible" :close-on-press-escape="false" :close-on-click-modal="false"
      @closed="dialogClosed" width="40%">
      <el-form ref="postForm" :model="form" :rules="rules" class="form-container">
        <div class="createPost-main-container">
          <el-form-item label-width="120px" label="顺序:" prop="order">
            <el-input v-model="form.order" class="input-spin" type="number" />
          </el-form-item>
          <el-form-item label-width="120px" label="轮播图名称:" prop="name">
            <el-input v-model.trim="form.name" />
          </el-form-item>
          <el-form-item label-width="120px" label="上传图片:" prop="image_url">
            <el-upload :file-list="fileList" action="#" :limit="1" accept=".jpg,.jpeg,.png,.JPG,.JPEG" list-type="picture-card"
              :http-request="(file) => { return uploadImgHandle(file, index)}"
              :on-remove="(file, fileList) => { return removeHandle(file, fileList, index)}" :class="{hide:fileList.length > 0}">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-top: 40px;text-align: center;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleToggleEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCarouselList,
    deleteCarousel,
    createCarousel,
    updateCarousel,
    uploadFile
  } from '@/api/common'
  import waves from '@/directive/waves' // waves directive

  export default {
    name: 'settingCarousel',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        dialogVisible: false,
        type: 0,
        fileList: [],
        form: {
          order: undefined,
          name: undefined,
          image_url: undefined
        },
        rules: {
          order: [{
            required: true,
            message: '请输入顺序',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入轮播图名',
            trigger: 'blur'
          }],
          image_url: [{
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }]
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      removeHandle(file, fileList, index) {
        this.form.image_url = undefined;
        this.fileList = [];
      },
      uploadImgHandle(e) {
        var formData = new FormData();
        formData.append('file', e.file);
        uploadFile(formData).then((res) => {
          const image = res.data
          this.fileList = [{
            url: this.$store.state.settings.imgHost + image
          }];
          this.form.image_url = image;
        });
      },
      getList() {
        this.listLoading = true
        getCarouselList().then(response => {
          this.list = response.data
        }).finally(() => {
          this.listLoading = false
        })
      },
      // 编辑
      handleUpdate(row) {
        this.type = 1;
        this.form = Object.assign({}, row);
        this.fileList = [{
          url: this.$store.state.settings.imgHost + row.image_url
        }];
        this.dialogVisible = true;
      },
      // 新增
      handleCreate() {
        this.type = 0;
        this.dialogVisible = true;
      },
      dialogClosed() {
        this.form = {
          order: undefined,
          name: undefined,
          image_url: undefined
        }
        this.fileList = [];
        this.$refs["postForm"].resetFields();
      },
      // 处理新增||处理编辑
      handleToggleEdit() {
        this.$refs.postForm.validate(async (valid, object) => {
          if (valid) {
            if (this.type == 0) {
              createCarousel(this.form).then(() => {
                this.$notify({
                  title: '提示',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000
                })
                this.dialogVisible = false;
                this.getList();
              })
            } else {
              const params = {
                order: this.form.order.toString(),
                name: this.form.name,
                image_url: this.form.image_url
              }
              updateCarousel(this.form["id"], params).then(() => {
                this.$notify({
                  title: '提示',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                })
                this.dialogVisible = false;
                this.getList();
              })
            }
          }
        })
      },
      // 删除
      handleDelete(id) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          deleteCarousel(id).then(() => {
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(() => {
            this.listLoading = false
          })
        }).catch(() => { })
      }
    }
  }
</script>

<style>
  .el-upload-list__item.is-ready,
  .el-upload-list__item.is-uploading {
    display: none !important;
  }

  .hide .el-upload--picture-card {
    display: none;
  }

  .el-upload-list__item {
    transition: none !important;
  }
</style>